package com.my.study.juc;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.locks.LockSupport;

/**
 * LockSupport是一个线程阻塞工具类，所有的方法都是静态方法，可以让线程在任意位置阻塞，当然阻塞之后肯定得有唤醒的方法。
 *
 * @author: yidujun
 * @create: 2021/03/29 19:15
 */
@Slf4j
public class LockSupportTest {

    public static final Object U = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            synchronized (U) {
                System.out.println("in " + getName());
                LockSupport.park();
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(getName() + "被中断了");
                }
                System.out.println(getName() + "继续执行");
            }
        }
    }

    @Test
    public void test01() throws InterruptedException {
        Thread currentThread = Thread.currentThread();
        Instant now1 = Instant.now();
        t1.start();
        Thread.sleep(1000L);
        System.out.println(currentThread.getName() + "1 -> " + Duration.between(now1, Instant.now()).toNanos());
        Instant now2 = Instant.now();
        t2.start();
        Thread.sleep(3000L);
        System.out.println(currentThread.getName() + "2 -> " + Duration.between(now2, Instant.now()).toNanos());
        t1.interrupt();
        LockSupport.unpark(t2);
        t1.join();
        t2.join();
    }
}
